'use strict'

const fs = require('fs');
const router = require('koa-router')();

// 获取文件名
function getFileName(path) {
    let dirpath = path || __dirname;
    let file = fs.readdirSync(dirpath);
    let files = file.filter(item => {
        return item.endsWith('.js') && item !== 'index.js'
    })
    return files;
}

// 注册路由
function registerRouter(filename, router) {
    filename.forEach(item => {
        let filePath = __dirname + '/' + item;
        let obj = require(filePath);

        for (let key in obj) {
            let tmpArr = key.split(' ');
            let request = tmpArr[0];
            let tmppath = tmpArr[1];
            let tmpfn = obj[key];

            if (request === 'get') {
                router.get(tmppath, tmpfn);
            } else if (request === 'post') {
                router.post(tmppath, tmpfn)
            } else if (request === 'put') {
                router.put(tmppath, tmpfn)
            } else if (request === 'delete') {
                router.delete(tmppath, tmpfn)
            } else {
                console.log('请求方式错误！');
            }
        }
    });
    return router.routes();
}

module.exports = function () {
    let fileName = getFileName();
    let fn = registerRouter(fileName, router)
    return fn;
}